define(function(require){
    var main = require('/static/main.js');
    require('/static/ajaxfileupload.js');
    var m = new main();
    var bbargin = {
        vueData:'',
        um : UM.getEditor('myEditor'),
        ActGroupId:$_GET['id'],
        _init:function(){
            this.ajaxUpload('MainSrc');
            this.ajaxUpload('ShopMainSrc');
            this.ajaxUpload('wxMainSrc');
            this.ajaxUpload('CoverSrc');

            if(bbargin.ActGroupId){
                m.loadmenu('.cate-drainage',1);
                $('.q-tit-change').html('<a href="/drainage/bargainactive">砍价活动管理</a> > 编辑');
                $('.SaveBtn').html('完成');
                this.getdetial();
            }else{
                m.loadmenu('.cate-drainage',0);
            }

            this.bindValue();
            this.bindEvent();
            bbargin.bindKeyEvent($(".GroupPrice"),'.groupprice');
            bbargin.bindKeyEvent($(".OriginalPrice"),'.originalprice');
        },
        bindValue:function(){
            //内容框输入
            $('.p-yl2').keyup(function (e) {
                var className = $(this).data("classname");
                $("#ShowMessage ."+className).text($(this).val());
            });
            bbargin.um.addListener( "contentchange", function () {
                $(".goods-details").html(UM.getEditor('myEditor').getContent());

            } );

        },

        getdetial:function(){
            var _this = this;
            $.ajax({
                type: "POST",
                url:'/drainage/group-detial',
                data:{ActGroupId:bbargin.ActGroupId},
                dataType: "json",
                success: function (ret) {
                    if(ret.IsBizSuccess){
                        var v = ret.Model;
                        //console.log(v);
                        //活动信息
                        $('.col-md-7 .ActBargainName').val(v.ActName);
                        $(".head_tit_center").html(v.ActName);
                        $('#CoverSrc').attr('data-src',v.CoverSrc);
                        $('#StartDate').val(m.formatTimeAll2(v.StartTime));
                        $('#EndDate').val(m.formatTimeAll2(v.EndTime));
                        _this.countTime(m.formatTimeAll2(v.EndTime),m.formatTimeAll2(v.StartTime));
                        if(v.IsOpen){
                            $(".isopen").click();
                        }
                        //商品信息
                        $('.seckill-prosrc img').attr({'src':v.ProductSrc,'data-src':v.ProductSrc}); //商品主图
                        bbargin.setVal(v.ProductName,'ProductName');
                        bbargin.setVal(v.Comment,'Comment');
                        if(v.BounsPrdType == 200){
                            $('.receiveWay1').hide();
                            $('.receiveWay2').hide();
                            $('.receiveWay3').hide();
                        }
                        $('#ShopType option').each(function(){
                            if($(this).val() == v.BounsPrdType){
                                $(this).attr('selected',true);
                            }else{
                                $(this).removeAttr('selected');
                            }
                        })
                        // 如果 是 类型是 BounsPrdType 200 其他2个不能点击
                        $('#ShopFreeWay option').each(function(){
                            if($(this).val() == v.DeliveryType){
                                $(this).attr('selected',true);
                            }else{
                                $(this).removeAttr('selected');
                            }
                            if(v.BounsPrdType == 200){
                                if(parseInt($(this).val()) == 200 || parseInt($(this).val()) == 300){
                                    $(this).attr('disabled',true);
                                }else{
                                    $(this).removeAttr('disabled');
                                }
                            }
                        });

                        if(v.DeliveryType == 100){
                            $('.receiveWay1').hide()
                            $('.receiveWay2').hide()
                            $('.receiveWay3').hide()
                        }else if(v.DeliveryType == 200){
                            $('.receiveWay1').show()
                            $('.receiveWay2').hide();
                            $('.receiveWay3').show();
                        }else if(v.DeliveryType == 300){
                            $('.receiveWay1').hide();
                            $('.receiveWay2').show();
                            $('.receiveWay3').show();
                        }

                        UM.getEditor('myEditor').setContent(v.ProductDetial);
                        $('.ReceiveAdd').val(v.ReceiveAdd);
                        $('.NoticeTel').val(v.NoticeTel);
                        $('.Hotline').val(v.Hotline);
                        //配置信息
                        $('.GroupPrice').val(v.GroupPrice);
                        $("#ShowMessage .groupprice").text(v.GroupPrice);
                        $('.OriginalPrice').val(v.OriginalPrice);
                        $("#ShowMessage .originalprice").text(v.OriginalPrice);
                        $('.ActCnt').val(v.ActCnt);
                        bbargin.setVal(v.GroupScale,'GroupScale');
                        $('.GroupPeriod').val(v.GroupPeriod);
                        bbargin.setVal(v.Lightspot1,'Lightspot1');
                        bbargin.setVal(v.Lightspot2,'Lightspot2');
                        bbargin.setVal(v.Lightspot3,'Lightspot3');
                        $('.ShareTitle').val(v.ShareTitle);
                        $('.ShareContent').val(v.ShareContent);
                        $('#wxMainSrc').attr('data-src',v.ShareSrc)
                    }else{
                        layer.msg(ret.ErrMsg);
                        return false;
                    }
                }
            });
        },
        setVal:function(data,classname){
            $("#ShowMessage ."+classname).text(data);
            $(".col-md-7 ."+classname).val(data);
        },
        bindEvent:function(){
            var _this = this;
            var start = '';
            //初始化日期控件
            $('#StartDate').datetimepicker({
                format:'yyyy-mm-dd hh:ii',
                language:'zh-CN',
                autoclose: true,
                'startDate':new Date()
            }).on("changeDate",function(ev){
                start = $("#StartDate").val();
                $('#EndDate').datetimepicker('setStartDate',start);
                _this.countTime(start);

            });
            $('#EndDate').datetimepicker({
                format:'yyyy-mm-dd hh:ii',
                language:'zh-CN',
                autoclose: true,
                'startDate':new Date()
            }).on("changeDate",function(ev){
                var endtime = $("#EndDate").val();
                $('#StartDate').datetimepicker('setEndDate',endtime)
                _this.countTime(endtime,start)
            });

            // 选择配送方式 等 联动事件
            $('#ShopType').change(function(e){
                // alert(1);
                var val = $(this).children('option:selected').val()
                if(!bbargin.ActGroupId){
                    $('.receiveWay1').find('input').val('');
                    $('.receiveWay2').find('input').val('');
                    $('.receiveWay3').find('input').val('');
                }
                // if(val == 100){
                $('#ShopFreeWay option').each(function(){
                    if(val == 100){
                        if(parseInt($(this).val()) == 100){
                            $(this).attr('disabled',true);
                        }else{
                            $(this).removeAttr('disabled');
                        }
                        if(parseInt($(this).val()) == 200){
                            $(this).attr('selected',true);
                        }else{
                            $(this).removeAttr('selected');
                        }
                        $('.receiveWay1').show()
                        $('.receiveWay2').hide()
                        $('.receiveWay3').show()
                    }else if(val == 200){
                        $('.receiveWay1').hide()
                        $('.receiveWay2').hide()
                        $('.receiveWay3').hide()
                        if(parseInt($(this).val()) == 200 || parseInt($(this).val()) == 300){
                            $(this).attr('disabled',true);
                        }else{
                            $(this).removeAttr('disabled');
                        }
                        if(parseInt($(this).val()) == 100){
                            $(this).attr('selected',true);
                        }else{
                            $(this).removeAttr('selected');
                        }
                    }
                })
                // }else{
                // }

            })
            // 判断那种领取方式
            $('#ShopFreeWay').change(function(e){
                var val = $(this).children('option:selected').val()
                if(!bbargin.ActGroupId){
                    $('.receiveWay1').find('input').val('');
                    $('.receiveWay2').find('input').val('');
                    $('.receiveWay3').find('input').val('');
                }

                if(val == 100){
                    $('.receiveWay1').hide()
                    $('.receiveWay2').hide()
                    $('.receiveWay3').hide()
                }
                if(val == 200){
                    $('.receiveWay1').show()
                    $('.receiveWay2').hide();
                    $('.receiveWay3').show();
                }
                if(val == 300){
                    $('.receiveWay1').hide();
                    $('.receiveWay2').show();
                    $('.receiveWay3').show();
                }
            })

            // 创建活动
            $('.SaveBtn').click(function(){
                var $this = $(this);
                var data = {
                    // 活动信息
                    ActName:$('.col-md-7 .ActBargainName').val(),
                    ProductSrc:$('.seckill-prosrc img').attr('data-src'),
                    StartTime:$('#StartDate').val(),
                    EndTime:$('#EndDate').val(),
                    IsOpen:$('.isuseable').is(":checked"),
                    CoverSrc: $('#CoverSrc').attr('data-src'),

                    ProductName:$('.col-md-7 .ProductName').val(),
                    Comment:$('.col-md-7 .Comment').val(),
                    BounsPrdType:$('#ShopType option:selected').val(),
                    DeliveryType:$('#ShopFreeWay option:selected').val(),
                    ReceiveAdd:$('.ReceiveAdd').val(),
                    NoticeTel:$('.NoticeTel').val(),
                    Hotline:$('.Hotline').val(),
                    ProductDetial:UM.getEditor('myEditor').getContent(),
                    // 配置信息
                    GroupPrice:$('.GroupPrice').val(),
                    OriginalPrice:$('.OriginalPrice').val(),
                    ActCnt:$('.ActCnt').val(),
                    GroupScale:$('.col-md-7 .GroupScale').val(),
                    GroupPeriod:$('.GroupPeriod').val(),
                    Lightspot1:$('.col-md-7 .Lightspot1').val(),
                    Lightspot2:$('.col-md-7 .Lightspot2').val(),
                    Lightspot3:$('.col-md-7 .Lightspot3').val(),

                    // 微信分享
                    ShareTitle:$('.ShareTitle').val(),
                    ShareContent:$('.ShareContent').val(),
                    ShareSrc:$('#wxMainSrc').attr('data-src'),
                }

                // console.log(data);
                // return false
                var alltrue = true;
                var truearrya = [];
                data.ProductSrc = data.ProductSrc == undefined ? '' : data.ProductSrc
                data.ShareSrc = data.ShareSrc == undefined ? '' : data.ShareSrc
                data.CoverSrc = data.CoverSrc == undefined ? '' : data.CoverSrc

                truearrya.push( bbargin.errorMessage(data.ActName,'actbargainname','请填写活动名称'));
                truearrya.push( bbargin.errorMessage(data.CoverSrc,'coversrc','请上传活动封面图'));
                truearrya.push( bbargin.errorMessage(data.StartTime,'startdate','请选择活动开始时间'));
                truearrya.push( bbargin.errorMessage(data.EndTime,'enddate','请选择活动结束时间'));
                if(parseInt(data.BounsPrdType) == 100){
                    if(parseInt(data.DeliveryType) == 200){
                        truearrya.push( bbargin.errorMessage(data.ReceiveAdd,'receiveadd','请填写线下领取地址'));
                    }else if(parseInt(data.DeliveryType) == 300){
                        truearrya.push( bbargin.errorMessage(data.NoticeTel,'noticetel','请填写订单提醒电话'));
                    }
                    truearrya.push( bbargin.errorMessage(data.Hotline,'hotline','请填写活动咨询电话'));
                }


                truearrya.push( bbargin.errorMessage(data.ProductSrc,'poductsrc','请上传商品主图'));
                truearrya.push( bbargin.errorMessage(data.ProductName,'productname','请填写商品名称'));
                truearrya.push( bbargin.errorMessage(data.Comment,'comment','请填写商品描述'));
                truearrya.push( bbargin.errorMessage(data.ProductDetial,'productdetial','请填写商品详情'));
                truearrya.push( bbargin.errorMessage(data.GroupPrice,'groupprice','目标价格不能为空'));
                truearrya.push( bbargin.errorMessage(data.OriginalPrice,'originalprice','原始价格不能为空'));
                truearrya.push( bbargin.errorMessage(data.ActCnt,'actcnt','请输入活动名额'));
                truearrya.push( bbargin.errorMessage(data.GroupScale,'groupscale','请输入拼团规模'));
                var ActCnt = parseInt(data.ActCnt);
                var GroupScale = parseInt(data.GroupScale);
                if(ActCnt % GroupScale > 0){
                    truearrya.push(false);
                    $(".pass-msg.actcnt").html('活动名额需为拼团规模的倍数');
                }

                truearrya.push( bbargin.errorMessage(data.GroupPeriod,'groupperiod','开团有效期'));
                truearrya.push( bbargin.errorMessage(data.Lightspot1,'lightspot1','请输入配置亮点1'));
                truearrya.push( bbargin.errorMessage(data.Lightspot2,'lightspot2','请输入配置亮点2'));
                truearrya.push( bbargin.errorMessage(data.Lightspot3,'lightspot3','请输入配置亮点3'));



                truearrya.push( bbargin.errorMessage(data.ShareTitle,'sharetitle','请填写微信分享标题'));
                truearrya.push( bbargin.errorMessage(data.ShareContent,'sharecontent','请填写微信分享内容'));
                truearrya.push( bbargin.errorMessage(data.ShareSrc,'sharesrc','请上传微信分享图片'));


                $.each(truearrya,function(k,v){
                    if(v == false){
                        alltrue = false;
                        return false;
                    }
                });
                if(bbargin.ActGroupId){
                    data.ActGroupId = bbargin.ActGroupId
                }
                // console.log(data);
                // return false
                data.ProductSrc = _this.GetUrlRelativePath(data.ProductSrc);
                data.ShareSrc = _this.GetUrlRelativePath(data.ShareSrc);
                data.CoverSrc = _this.GetUrlRelativePath(data.CoverSrc);

                if(alltrue){
                    var isclick = parseInt($this.attr('isclick'));
                    if(isclick == 1){
                        $.ajax({
                            type: "POST",
                            url: "/drainage/group-buy-create",
                            data :data,
                            dataType: "json",
                            success: function (ret){
                                if(ret.IsBizSuccess){
                                    if(bbargin.ActGroupId){
                                        layer.msg("编辑成功");
                                    }else{
                                        layer.msg("创建成功");
                                    }
                                    $this.attr('isclick',0);
                                    setTimeout(function(){
                                        window.location.href="/drainage/group";
                                    },1000)
                                    return false;
                                }else{
                                    layer.msg(ret.msg);
                                }
                            }
                        });
                    }

                }
            });
            $(".ProductDetial").click(function(){
                $("#Detail").modal('show');
            });
            $("#Detail .btn-sure").click(function(){
                $("#Detail").modal('hide');
            });

        },
        //错误处理
        errorMessage:function(str,classname,errmsg){
            if(str.length < 1){
                var html = $(".pass-msg."+classname).html();
                if(html.length < 1){
                    $(".pass-msg."+classname).html(errmsg);
                }
                return false;
            }else{
                $(".pass-msg."+classname).html("");
                return true
            }
        },
        //倒计时
        countTime:function(endTime,startTime){
            var _this = this;
            //倒计时
            var timesTramp =  Date.parse(endTime)/1000
            var timestmp = startTime ? Date.parse(startTime)/1000 : Date.parse(new Date())/1000
            var ts =  (timesTramp - timestmp);//计算剩余的毫秒数
            var day = 0, hour = 0, minute = 0, second = 0; //时间默认值   
            day = parseInt(ts / (60 * 60 * 24));
            hour = parseInt(ts / (60 * 60)) - (day * 24);
            minute = parseInt(ts / 60) - (day * 24 * 60) - (hour * 60);
            second = parseInt(ts) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
            if (hour <= 9) hour = '0' + hour;
            if (minute <= 9) minute = '0' + minute;
            if (second <= 9) second = '0' + second;
            if(ts < 0){
                return false;
            }
            var str = '';
            if(day >0){
                str += '<span><i>'+day+'</i>天</span>';
            }

            str += '<span><i>'+hour+'</i>时</span>\
                    <span><i>'+minute+'</i>分</span>\
                    <span><i>'+second+'</i>秒</span>';
            $(".count-time").html(str);
        },
        //上传图片
        ajaxUpload:function(obj){
            $(document).on("change",'#'+obj,function(e){
                ajaxFileUpload();
            })
            function ajaxFileUpload(){
                $.ajaxFileUpload({
                    url:m.baseUrl+"/customer/edit-head",
                    secureuri: false,
                    fileElementId: obj,
                    dataType: 'json',
                    success: function (ret) {
                        if(ret.IsBizSuccess){
                            if(obj == 'MainSrc'){
                                $('.seckill-prosrc img').attr('src',ret.Photo);
                                $('.seckill-prosrc  img').attr('data-src',ret.FileName);
                            }else if(obj == 'ShopMainSrc'){
                                $('.seckill-prosrc img').attr('src',ret.Photo);
                                $('.seckill-prosrc img').attr('data-src',ret.FileName);
                            }else if(obj == 'wxMainSrc'){
                                $('#wxMainSrc').attr('data-src',ret.FileName);
                            }else if(obj == 'CoverSrc'){
                                $('#CoverSrc').attr('data-src',ret.FileName);
                            }
                            $('#'+obj).siblings('.input-group').find('input').attr('placeholder',ret.FileName);
                        }else{
                            layer.msg(ret.ErrMsg);
                            return false;
                        }
                    }
                })
                return false;
            }
        },
        //去除域名获取相对路径
        GetUrlRelativePath:function(url){
            var arrUrl = url.split("//");
            var length = arrUrl.length;
            if(length > 1){
                var start = arrUrl[length-1].indexOf("/");
                var relUrl = arrUrl[length-1].substring(start);//stop省略，截取从start开始到结尾的所有字符
                if(relUrl.indexOf("?") != -1){
                    relUrl = relUrl.split("?")[0];
                }
                if (relUrl.substr(0,1)=='/') {
                    relUrl = relUrl.substr(1);
                }
                return relUrl;
            }else{
                return url;
            }
        },
        bindKeyEvent:function(obj,classname){
            obj.keyup(function () {
                var reg = $(this).val().match(/\d+\.?\d{0,2}/);
                var txt = '';
                if (reg != null) {
                    txt = reg[0];
                }
                $(this).val(txt);
                $(".seckill-detail").find(classname).text(txt);
            }).change(function () {
                $(this).keypress();
                var v = $(this).val();
                if (/\.$/.test(v))
                {
                    $(this).val(v.substr(0, v.length - 1));
                    $(".seckill-detail").find(classname).text(v.substr(0, v.length - 1));
                }
            });
        },

    }

    // var ret = new Cont();
    bbargin._init();



})